package funcUtils

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

// HttpGet 发送GET请求
// url：请求地址
func HttpGet(url string) (map[string]interface{}, error) {
	client := &http.Client{Timeout: 5 * time.Second}
	fmt.Println("HttpGet请求三方接口信息：", url)
	resp, err := client.Get(url)
	if err != nil {
		fmt.Println("HttpGet调用三方接口出现了错误:", err)
		return nil, err
	}
	res, err := ioutil.ReadAll(resp.Body)
	fmt.Println("HttpGet三方接口返回信息：", bytes.NewBuffer(res), err)

	// 将 JSON 字符串转换为 map[string]interface{}
	var dataMap map[string]interface{}
	if err := json.Unmarshal([]byte(res), &dataMap); err != nil {
		fmt.Printf("Failed to unmarshal JSON: %v\n", err)
		return nil, err
	}

	return dataMap, nil
}

// HttpPost 发送POST请求
// url：         请求地址
// data：        POST请求提交的数据
// contentType： 请求体格式，如：application/json
func HttpPost(url string, data interface{}, contentType string) (map[string]interface{}, error) {
	//创建调用API接口的client
	client := &http.Client{Timeout: 5 * time.Second}
	jsonStr, _ := json.Marshal(data)
	fmt.Println("HttpPost请求三方接口信息：", url, bytes.NewBuffer(jsonStr))
	resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonStr))
	if err != nil {
		fmt.Println("HttpPost调用三方接口出现了错误:", err)
		return nil, err
	}
	res, err := ioutil.ReadAll(resp.Body)
	fmt.Println("HttpPost三方接口返回信息：", bytes.NewBuffer(res), err)

	// 将 JSON 字符串转换为 map[string]interface{}
	var dataMap map[string]interface{}
	if err := json.Unmarshal([]byte(res), &dataMap); err != nil {
		fmt.Printf("Failed to unmarshal JSON: %v\n", err)
		return nil, err
	}
	return dataMap, err
}
